//find the value of the cookie_name
function get_cookie ( cookie_name )
{
    var cookie_string = document.cookie ;
    if (cookie_string.length != 0) {
        var cookie_value = cookie_string.match (
                        cookie_name +
                        '=([^;]*)' );
		if(cookie_value!=null){
			return decodeURIComponent ( cookie_value[0].split("=")[1] ) ;
		}
		else{
			return '';
		}
    }
    return '' ;
}

function setDraggable() {
	$( "#sortable" ).sortable({
		revert: true
	});
	$( "ul, li" ).disableSelection();
};

function setSelectable() {
	$( "#listingTable" ).selectable({
			filter: 'tr',
			cancel: 'a'
	});
}



$(document).ready(function(){
	setSelectable();
	
	//check the cookies and style the page accordingly
	var firstname = get_cookie("Fname");
	if(firstname != ''){
		$("#accountdetails").text(firstname + "'s saved Posts");
		$("#accountLogin").text("Log out");
		$("#accountLogin").prop("href","");
		$("#accountLogin").prop("id","logout");
		$("#accountLogin").className = "logout";
	}
	else{
		$("#accountdetails").text("Make An Account Today");
		$("#accountdetails").prop("href","newAccount.php");
		$("#accountLogin").prop("class","modalbox");
	}
	//Handle the login request
	$("#accountLogin").click(function(){
		
	});
	
	//Opens the setting toolbar
	$("#settings_icon").click(function(){
		if($("#settingsContainer").attr("style") == "display: none;") {
			$("#settingsContainer").show();
		}
		else {
			$("#settingsContainer").hide();
		}
	});
	
	//Save post
	$("#save_icon").click(function(){
		$(".ui-selected").each(function() {
			var content = $(this).find('.replylink').text();
			var url = $(this).find('.replylink').attr('href');
			var image = $(this).find('img').attr('src');
			var parent = $(this).attr('class').substring(0, $(this).attr('class').indexOf("_post"));
			
			$.get("PHP/savePosts.php",
			{
				user: get_cookie('usr'),
				content: content,
				url: url,
				image: image,
				parent: parent
			},
			function(data) {
				alert("Post saved!" + data);
			});
			
		});
	});

	//Updates main table based on changes to chckbox filters
	$(document).on("change", ":checkbox", function() {
		$(":checkbox[name^='enable']").each(function() {
			if($(this).is(':checked'))
				$("."+$(this).attr('value')+"_post").show();
			else
				$("."+$(this).attr('value')+"_post").hide();
		});
	});
	
	//Updates main table based on search input
	$("[name='search_field']").on('input', function() {
			$(".replylink").each(function() {
				var search = $("[name='search_field']").val();
				if(search != "" && $(this).text().toLowerCase().indexOf(search) == -1)
					$(this).parent().parent().hide();
				else
					$(this).parent().parent().show();
			});
		
	});
	
	//Clears search box
	$("[value='Clear']").on("click", function () {
		$("[name='search_field']").val("");
		$(".replylink").each(function() {
			$(this).parent().parent().show();
		});
	});
	
	//Catches search form submission
	$("[rel='async']").submit(function() { return false; });
	
	//Changes input based on parser selected in the add parser pop-up
	$("#availableParsers").change(function() {
		$('.extraInput').hide();
		if($(this).val() == 'Reddit') {
			$("#extraSubredditInput").show();
		}
		else if($(this).val() == 'Gmail' ) {
			$("#extraGmailInput").show();
		}
	});
	
	$("#changeOrder").click( function() {
		if($(this).text() == 'Change Order') {
			$(this).text('Set Change');
			setDraggable();
		}
		else {
			var parsers = [];
			$(":checkbox[name^='enable']").each(function() {
				var t = 0;
				if($(this).is(':checked'))
					t=1;
				parsers.push($(this).attr('value')+"_"+t);
			});
			var ext = {};
			ext['parsers'] = parsers;
		
			$.ajax({ url: '?'+$.param(ext), dataType: 'html', 
				success: function(response) { 
					$('#mainResults').html(jQuery(response).find('#mainResults').html()); 
					$('#listofsettings').html(jQuery(response).find('#listofsettings').html()); 
					$("[name='search_field']").val("");
					$("#changeOrder").text('Change Order');
					setSelectable();
				} 
			});
		}
	});
	
	//Pop-up boxes
	$(".modalbox").fancybox();
	$("#contact").submit(function() { return false; });
	$("#sendAdd").on("click", function(){
		var parsers = [];
		$(":checkbox[name^='enable']").each(function() {
			var t = 0;
			if($(this).is(':checked'))
				t=1;
			parsers.push($(this).attr('value')+"_"+t);
		});
		
		if($("#availableParsers").val() == 'Reddit') {
			parsers.push('Reddit'+ $("#extraSubredditInput").val()+"_1");
		}
		else {
			parsers.push($("#availableParsers").val()+"_1");
		}
		var ext = {};
		ext['parsers'] = parsers;
		
		$.ajax({ url: '?'+$.param(ext), dataType: 'html', 
			success: function(response) { 
				$('#mainResults').html(jQuery(response).find('#mainResults').html()); 
				$('#listofsettings').html(jQuery(response).find('#listofsettings').html()); 
				$('#removableParsers').html(jQuery(response).find('#removableParsers').html()); 
				$("[name='search_field']").val("");
				$("#changeOrder").text('Change Order');
				setSelectable();
				setTimeout("$.fancybox.close()", 0);
			} 
		});
	});
	$("#sendRemove").on("click", function(){
		var parsers = [];
		$(":checkbox[name^='enable']").each(function() {
			var t = 0;
			if($("#removableParsers").val() != $(this).attr('value')) {
				if($(this).is(':checked'))
					t=1;
				parsers.push($(this).attr('value')+"_"+t);
			}
		});
			
		var ext = {};
		ext['parsers'] = parsers;
		
		$.ajax({ url: '?'+$.param(ext), dataType: 'html', 
			success: function(response) { 
				$('#mainResults').html(jQuery(response).find('#mainResults').html()); 
				$('#listofsettings').html(jQuery(response).find('#listofsettings').html()) 
				$('#removableParsers').html(jQuery(response).find('#removableParsers').html()); 
				$("[name='search_field']").val("");
				$("#changeOrder").text('Change Order');
				setSelectable();
				setTimeout("$.fancybox.close()", 0);
			} 
		});
	});
	
		$("#sendLogin").on("click", function(){
		    var txt = $('#Loginpassword');
			txt.val(CryptoJS.SHA256(txt.val()));
			var usr = $('#userName');
			usr.val(CryptoJS.SHA256(usr.val()));
			return true;
	});
		$("#logout").on("click", function(){
			document.cookie="usr=;";
			document.cookie="pass=;";
			document.cookie="Fname=;";
			document.cookie="Lname=;";
			document.cookie="urlVars=;";
			});
	
	});
	
	//from stack overflow
		$(window).scroll(function () { 
			if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
				//fetch a new page of content
				$.ajax({ url: '?parsers=', dataType: 'html', success: function(response) { $('#listingTableBody').append(jQuery(response).find('#listingTableBody').html()); } });
			}
	});
